package com.health.controller;

import com.health.dto.*;
import com.health.model.User;
import com.health.model.UserStatus;
import com.health.security.AdminRequired;
import com.health.service.UserService;
import com.health.security.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @PostMapping("/register")
    public ResponseEntity<ApiResponse<?>> register(@RequestBody RegisterRequest request) {
        try {
            User user = userService.register(request);
            return ResponseEntity.ok(ApiResponse.success(user));
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }
    
    @PostMapping("/login")
    public ResponseEntity<ApiResponse<?>> login(@RequestBody LoginRequest request) {
        try {
            User user = userService.login(request);
            String token = jwtUtil.generateToken(user.getId());
            
            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            data.put("user", user);
            
            return ResponseEntity.ok(ApiResponse.success(data));
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }
    
    @GetMapping("/test")
    public String test() {
        return "API is working!";
    }
    
    // 获取用户信息
    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<?>> getUserInfo(@PathVariable Long id) {
        try {
            User user = userService.getUserById(id);
            return ResponseEntity.ok(ApiResponse.success(user));
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }
    
    // 修改用户信息
    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<?>> updateUserInfo(
            @PathVariable Long id, 
            @RequestBody UpdateUserRequest request) {
        try {
            User user = userService.updateUser(id, request);
            return ResponseEntity.ok(ApiResponse.success(user));
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }
    
    // 修改密码
    @PutMapping("/{id}/password")
    public ResponseEntity<ApiResponse<?>> updatePassword(
            @PathVariable Long id, 
            @RequestBody UpdatePasswordRequest request) {
        try {
            userService.updatePassword(id, request);
            return ResponseEntity.ok(ApiResponse.success(null));
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }
    
    // 获取用户列表（管理员）
    @AdminRequired
    @GetMapping("/admin/list")
    public ResponseEntity<ApiResponse<?>> getUserList(UserPageRequest request) {
        try {
            PageResponse<User> response = userService.getUserList(request);
            return ResponseEntity.ok(ApiResponse.success(response));
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }
    
    // 添加用户（管理员）
    @AdminRequired
    @PostMapping("/admin/add")
    public ResponseEntity<ApiResponse<?>> addUser(@RequestBody RegisterRequest request) {
        try {
            User user = userService.addUser(request);
            return ResponseEntity.ok(ApiResponse.success(user));
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }
    
    // 更新用户状态（管理员）
    @AdminRequired
    @PutMapping("/admin/{id}/status")
    public ResponseEntity<ApiResponse<?>> updateUserStatus(
            @PathVariable Long id,
            @RequestParam UserStatus status) {
        try {
            userService.updateUserStatus(id, status);
            return ResponseEntity.ok(ApiResponse.success(null));
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }
    
    // 删除用户（管理员）
    @AdminRequired
    @DeleteMapping("/admin/{id}")
    public ResponseEntity<ApiResponse<?>> deleteUser(@PathVariable Long id) {
        try {
            userService.deleteUser(id);
            return ResponseEntity.ok(ApiResponse.success(null));
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }
    
    @GetMapping("/encode")
    public String encode(@RequestParam String password) {
        return passwordEncoder.encode(password);
    }
    
    @GetMapping("/test-password")
    public String testPassword() {
        return passwordEncoder.encode("123456");
    }
} 